import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes';
import store from '@/store';




Vue.use(VueRouter)

const originPush = VueRouter.prototype.push
VueRouter.prototype.push = function(location,onResolved,onRejectd) {
    if(onResolved === undefined && onRejectd === undefined) {
        //call修改this指向
        return originPush.call(this,location).catch(() => {       
        })
    }else {
        return originPush.call(this,location,onResolved,onRejectd)
    }
}
 

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to,from,savedPosition) {
      return {x: 0,y: 0}
  }
})

router.beforeEach( async (to, from, next) => {
    // console.log(store);
   let token = store.state.user.token
   let userInfo = store.state.user.userInfo.name
   console.log('userInfo1',userInfo);
   if(token) {
       //用户登录
       if(to.path === '/Login') {
           next('/')
       }else {
           if (userInfo) {
               next()
           }else {
               //请求获取用户信息
               try {
                   await store.dispatch('getUserInfo');
                   next()
               } catch (error) {
                   console.log(error.message);//token过期
                   //清理过期token
                    store.dispatch('clearToken')
                    next('/Login')
               }
           }
       }
   }else {
       let targetPath = to.path
       if(targetPath.indexOf('/Trade') !== -1 || targetPath.indexOf('/Pay') !== -1 || targetPath.startsWith('//Center')) {
            next('/Login?redirect='+targetPath)
       }else {
           next()
       }
   }
})
export default router
